<template>
  <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
    <div class="application">
      <a-space direction="horizontal" :size="16" style="margin-bottom: 16px;">
        <span>用户名</span>
        <a-select v-model:value="selectedUserId" placeholder="选择用户名" style="width: 200px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="user in users" :key="user.userId" :value="user.userId">
            {{ user.username }}
          </a-select-option>
        </a-select>
        <span>职位名</span>
        <a-input v-model:value="selectedJobTitle" placeholder="输入职位名" style="width: 200px;" />
        <span>状态</span>
        <a-select v-model:value="selectedStatus" placeholder="选择状态" style="width: 200px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="pending">待处理</a-select-option>
          <a-select-option value="rejected">已拒绝</a-select-option>
          <a-select-option value="hired">已录取</a-select-option>
          <a-select-option value="viewed">已查看</a-select-option>
          <a-select-option value="interviewed">已面试</a-select-option>
        </a-select>
        <a-button type="primary" @click="handleFilter">检索</a-button>
        <a-button @click="resetFilter">重置</a-button>
        <a-button type="primary" @click="addApplication">新增</a-button>
      </a-space>

      <a-table
          :columns="columns"
          :row-key="item => item.applicationId"
          :data-source="displayApplications"
          :pagination="pagination"
          :loading="isLoading"
          @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'userId'">
            <span>{{ getUserById(record.userId) }}</span>
          </template>
          <template v-if="column.dataIndex === 'jobId'">
            <span>{{ getJobById(record.jobId) }}</span>
          </template>
          <template v-if="column.dataIndex === 'resumeId'">
            <span>{{ getResumeById(record.resumeId) }}</span>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <span>{{ formatStatus(record.status) }}</span>
          </template>
          <template v-if="column.dataIndex === 'appliedAt'">
            <span>{{ formatDate(record.appliedAt) }}</span>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            <span>{{ formatDate(record.updatedAt) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary" @click="showModal(record)">编辑</a-button>
              <a-popconfirm title="是否确认删除?" ok-text="是" cancel-text="否" @confirm="deleteApplication(record)">
                <a-button danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </a-layout-content>

  <!-- 模态框：新增/编辑 -->
  <a-modal v-model:open="open" title="编辑申请" :confirm-loading="confirmLoading" @ok="handleOk">
    <a-form ref="formRef" :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="用户ID" name="userId">
        <a-select v-model:value="formData.userId" show-search option-item-style="height: 30px;">
          <a-select-option v-for="user in users" :key="user.userId" :value="user.userId">
            {{ user.username }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="职位ID" name="jobId">
        <a-select v-model:value="formData.jobId" show-search option-item-style="height: 30px;">
          <a-select-option v-for="job in jobs" :key="job.jobId" :value="job.jobId">
            {{ job.title }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="简历ID" name="resumeId">
        <a-select v-model:value="formData.resumeId" show-search option-item-style="height: 30px;">
          <a-select-option v-for="resume in resumes" :key="resume.resumeId" :value="resume.resumeId">
            {{ resume.resumeTitle }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-select v-model:value="formData.status" style="width: 100%">
          <a-select-option value="pending">待处理</a-select-option>
          <a-select-option value="rejected">已拒绝</a-select-option>
          <a-select-option value="hired">已录取</a-select-option>
          <a-select-option value="viewed">已查看</a-select-option>
          <a-select-option value="interviewed">已面试</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="申请时间">
        <a-date-picker v-model:value="formData.appliedAt" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
      </a-form-item>
      <a-form-item label="更新时间">
        <a-date-picker v-model:value="formData.updatedAt" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';

const open = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);

// 数据源
const applications = ref<Application[]>([]);
const displayApplications = ref<Application[]>([]);
const users = ref<User[]>([]);
const jobs = ref<Job[]>([]);
const resumes = ref<Resume[]>([]);

interface Pagination {
  current: number;
  pageSize: number;
  total?: number;
}

const pagination = ref<Pagination>({
  pageSize: 10,
  total: 0,
  current: 1,
});

const isLoading = ref(true);
const searchKeyword = ref<string>('');
const isSearch = ref(false);

// 格式化函数
const formatDate = (date: string | Date): string => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '';
};

const formatStatus = (status: string): string => {
  switch (status) {
    case 'pending': return '待处理';
    case 'rejected': return '已拒绝';
    case 'hired': return '已录取';
    case 'viewed': return '已查看';
    case 'interviewed': return '已面试';
    default: return status;
  }
};

const getUserById = (id: number): string => {
  const user = users.value.find(u => u.userId === id);
  return user ? user.username : String(id);
};

const getJobById = (id: number): string => {
  const job = jobs.value.find(j => j.jobId === id);
  return job ? job.title : String(id);
};

const getResumeById = (id: number): string => {
  const resume = resumes.value.find(r => r.resumeId === id);
  return resume ? resume.resumeTitle : String(id);
};

// 分页逻辑
const handleTableChange = (pag: Pagination) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  if (!isSearch.value) {
    fetchApplications();
  } else {
    handleSearch();
  }
};

// 获取数据
const fetchApplications = async () => {
  try {
    isLoading.value = true;
    const res = await axios.get('/applications/list', {
      params: {
        page: pagination.value.current,
        size: pagination.value.pageSize,
      },
    });
    isLoading.value = false;
    pagination.value.total = res.data.data.total;
    applications.value = res.data.data.list;
    displayApplications.value = [...applications.value];

    if (applications.value.length === 0 && pagination.value.current > 1) {
      pagination.value.current -= 1;
      fetchApplications();
    }
  } catch (err) {
    console.error('请求失败:', err);
    isLoading.value = false;
  }
};

// 获取用户列表
const fetchUsers = async () => {
  try {
    const res = await axios.post('/users/query', {});
    users.value = res.data.data || [];
  } catch (err) {
    console.error('获取用户失败:', err);
  }
};

// 获取职位列表
const fetchJobs = async () => {
  try {
    const res = await axios.get('/jobs/list', { params: { page: 1, size: 9999 } });
    jobs.value = res.data.data.list || [];
  } catch (err) {
    console.error('获取职位失败:', err);
  }
};

// 获取简历列表
const fetchResumes = async () => {
  try {
    const res = await axios.get('/resumes/list', { params: { page: 1, size: 9999 } });
    resumes.value = res.data.data.list || [];
  } catch (err) {
    console.error('获取简历失败:', err);
  }
};

// 弹窗逻辑
const showModal = (record: Application) => {
  open.value = true;
  formData.value = {
    applicationId: record.applicationId,
    userId: record.userId,
    jobId: record.jobId,
    resumeId: record.resumeId,
    status: record.status,
    appliedAt: record.appliedAt ? dayjs(record.appliedAt) : undefined,
    updatedAt: record.updatedAt ? dayjs(record.updatedAt) : undefined,
  };
};

const addApplication = () => {
  open.value = true;
  formData.value = {
    applicationId: 0,
    userId: undefined,
    jobId: undefined,
    resumeId: undefined,
    status: 'pending',
    appliedAt: dayjs(),
    updatedAt: undefined,
  };
};

const handleOk = () => {
  if (formData.value.applicationId === 0) {
    doAddApplication();
  } else {
    updateApplication();
  }
};

const doAddApplication = () => {
  confirmLoading.value = true;
  axios.post('/applications/update', {
    userId: formData.value.userId,
    jobId: formData.value.jobId,
    resumeId: formData.value.resumeId,
    status: formData.value.status,
    appliedAt: formatDate(formData.value.appliedAt),
    updatedAt: formData.value.updatedAt ? formatDate(formData.value.updatedAt) : null,
  }).then(res => {
    if (res.data.code === 200) {
      message.success('添加成功');
      fetchApplications();
    } else {
      message.error('添加失败');
    }
    confirmLoading.value = false;
    open.value = false;
  }).catch(() => {
    message.error('网络错误，请重试');
    confirmLoading.value = false;
    open.value = false;
  });
};

const updateApplication = () => {
  confirmLoading.value = true;

  // 如果更新时间为空，则填充当前时间
  if (!formData.value.updatedAt) {
    formData.value.updatedAt = dayjs();
  }

  axios.post('/applications/update', {
    applicationId: formData.value.applicationId,
    userId: formData.value.userId,
    jobId: formData.value.jobId,
    resumeId: formData.value.resumeId,
    status: formData.value.status,  // 确保状态字段被正确传递
    appliedAt: formatDate(formData.value.appliedAt),
    updatedAt: formatDate(formData.value.updatedAt),
  }).then(res => {
    if (res.data.code === 200) {
      message.success('更新成功');
      fetchApplications();
    } else {
      message.error('更新失败');
    }
    confirmLoading.value = false;
    open.value = false;
  }).catch(() => {
    message.error('网络错误，请重试');
    confirmLoading.value = false;
    open.value = false;
  });
};

const deleteApplication = (record: Application) => {
  axios.post('/applications/delete', {
    applicationId: record.applicationId,
  }).then(() => {
    message.success('删除成功');
    if (!isSearch.value) {
      fetchApplications();
    } else {
      handleSearch();
    }
  }).catch(() => {
    message.error('删除失败，请稍后重试');
  });
};

const handleSearch = () => {
  isLoading.value = true;
  axios.post('/applications/query', {
    userId: searchKeyword.value || undefined,
    jobId: searchKeyword.value || undefined,
    resumeId: searchKeyword.value || undefined,
  }).then(res => {
    if (res.data.code === 200) {
      isSearch.value = true;
      pagination.value.total = res.data.data.length;
      applications.value = res.data.data;
      displayApplications.value = [...applications.value];
      isLoading.value = false;
      message.success('搜索成功');
    } else {
      message.error('搜索失败');
    }
  }).catch(() => {
    message.error('搜索失败，请稍后重试');
    isLoading.value = false;
  });
};

// 新增变量：用于存储输入的职位名
const selectedJobTitle = ref<string>('');

// 新增筛选相关变量
const selectedUserId = ref<number | ''>('');
const selectedJobId = ref<number | ''>('');
const selectedStatus = ref<string>('');

// 筛选方法
const handleFilter = () => {
  isLoading.value = true;
  axios.post('/applications/query', {
    userId: selectedUserId.value || undefined,
    jobId: selectedJobId.value || undefined,
  }).then(res => {
    if (res.data.code === 200) {
      isSearch.value = true;
      pagination.value.total = res.data.data.length;
      applications.value = res.data.data;
      // 在前端进行状态和职位名的模糊筛选
      displayApplications.value = applications.value.filter(app =>
          (!selectedStatus.value || app.status === selectedStatus.value) &&
          (!selectedJobTitle.value || getJobById(app.jobId).includes(selectedJobTitle.value))
      );
      isLoading.value = false;
      message.success('筛选成功');
    } else {
      message.error('筛选失败');
    }
  }).catch(() => {
    message.error('筛选失败，请稍后重试');
    isLoading.value = false;
  });
};

// 重置筛选方法
const resetFilter = () => {
  selectedUserId.value = '';
  selectedJobId.value = '';
  selectedJobTitle.value = ''; // 重置职位名
  selectedStatus.value = '';
  fetchApplications();
};

// 类型定义
interface Application {
  applicationId: number;
  userId: number;
  jobId: number;
  resumeId: number;
  status: string;
  appliedAt: string;
  updatedAt: string | null;
}

interface User {
  userId: number;
  username: string;
}

interface Job {
  jobId: number;
  title: string;
}

interface Resume {
  resumeId: number;
  resumeTitle: string;
}

const formData = ref<Application>({
  applicationId: 0,
  userId: 0,
  jobId: 0,
  resumeId: 0,
  status: 'pending',
  appliedAt: '',
  updatedAt: null,
});

const columns = [
  { title: '用户名', dataIndex: 'userId' },
  { title: '职位名', dataIndex: 'jobId' },
  { title: '简历标题', dataIndex: 'resumeId' },
  { title: '状态', dataIndex: 'status' },
  { title: '申请时间', dataIndex: 'appliedAt' },
  { title: '更新时间', dataIndex: 'updatedAt' },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    width: 150,
  },
];

onMounted(async () => {
  await Promise.all([fetchUsers(), fetchJobs(), fetchResumes()]);
  await fetchApplications();
});
</script>